package com.bins.music.player.ui;

import com.bins.music.player.model.PlayListBO;
import com.bins.music.player.model.SoundBO;
import com.bins.music.player.util.cloud.CloudMusicSpider;
import com.bins.music.player.util.cloud.CloudRequest;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class MusicPlayerUI extends BorderPane {
    
    private MediaPlayer mediaPlayer;
    private boolean isPlaying = false;
    final private List<SoundBO> playList = new ArrayList<>();
    private List<File> musicFiles;

    private ArrayList<PlayListBO> playListBOList;

    // 播放列表的TableView
    private TableView<SoundBO> playlistTableView;

    private int currentSongIndex = 0;
    
    // UI组件
    private Label currentSongLabel;
    private Label currentArtistLabel;
    private Slider progressSlider;
    private Label currentTimeLabel;
    private Label totalTimeLabel;
    private ImageView albumArt;
    private Button playButton;
    private Button prevButton;
    private Button nextButton;
    private Button likeButton;

    private Timeline progressTimeline;

    private final CloudRequest cloudRequest;

    private final CloudMusicSpider cloudMusicSpider;
    
    public MusicPlayerUI(Stage stage) {
        initializePlaylist();
        cloudRequest = new CloudRequest();
        cloudMusicSpider = new CloudMusicSpider();

        Color color1 = Color.rgb(114, 114, 114);

        Border border = new Border(new BorderStroke(
                color1, color1, color1, color1,/*四个边的颜色*/
                BorderStrokeStyle.SOLID,/*四个边的线型--实线*/
                BorderStrokeStyle.SOLID,
                BorderStrokeStyle.SOLID,
                BorderStrokeStyle.SOLID,
                new CornerRadii(5),
                new BorderWidths(1),
                new Insets(1, 1, 1, 1)
        ));

        int playListBeanListSize = 18;
        playListBOList = new ArrayList<>(playListBeanListSize);

        playlistTableView = new TableView<>();
        playlistTableView.setBorder(border);
        playlistTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        playlistTableView.setPrefWidth(540);
        createUI(stage);
        setupEventHandlers();
    }
    
    private void initializePlaylist() {
        // 模拟播放列表数据
//        playList.add(new Sound("1", "丢了你", "井胧", 125, "default-album.png"));
//        playList.add(new Sound("2", "兼葭", "andy", 230, "default-album.png"));
//        playList.add(new Sound("3", "梦里花", "苏星婕", 305, "default-album.png"));
//        playList.add(new Sound("4", "VIP", "壹", 180, "default-album.png"));

        musicFiles = new ArrayList<>();
        
        // 初始化媒体播放器
        // loadSong(0);
    }
    
    private void createUI(Stage stage) {
        // 设置背景色
        setStyle("-fx-background-color: #f5f5f5;");
        
        // 创建顶部搜索栏
        createTopBar(stage);
        
        // 创建左侧导航栏
        createLeftNav();
        
        // 创建中间内容区域
        // createContentArea();
        
        // 创建底部播放控制条
        createPlayerControl();
    }
    
    private void createTopBar(Stage stage) {
        HBox topBar = new HBox();
        topBar.setStyle("-fx-background-color: #ec4141; -fx-padding: 15;");
        topBar.setAlignment(Pos.CENTER_LEFT);
        topBar.setSpacing(20);
        
        // 应用标题
        Label titleLabel = new Label("网易云音乐风格播放器");
        titleLabel.setStyle("-fx-text-fill: white; -fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 搜索框
        TextField searchField = new TextField();
        searchField.setPromptText("搜索音乐");
        searchField.setPrefWidth(300);
        searchField.setStyle("-fx-background-radius: 20; -fx-border-radius: 20;");

        // 添加搜索框事件处理
        setupSearchEvents(searchField);
        
        HBox.setHgrow(searchField, Priority.ALWAYS);
        
        // 用户信息区域
        HBox userInfo = new HBox();
        userInfo.setAlignment(Pos.CENTER_RIGHT);
        userInfo.setSpacing(10);
        
        // 用户头像
        Circle userAvatar = new Circle(15, Color.WHITE);
        
        Label userName = new Label("用户");
        userName.setStyle("-fx-text-fill: white; -fx-font-size: 14px;");
        
        userInfo.getChildren().addAll(userAvatar, userName);


        // 控制按钮
        Button minimizeBtn = new Button("_");
        Button maximizeBtn = new Button("□");
        Button closeBtn = new Button("✕");

        // 控制按钮容器
        HBox windowControls = new HBox(4);
        windowControls.setAlignment(Pos.CENTER_RIGHT);
        windowControls.getChildren().addAll(minimizeBtn, maximizeBtn, closeBtn);
        windowControls.getStyleClass().add("window-controls");

        // 绑定按钮事件
        minimizeBtn.setOnAction(e -> stage.setIconified(true));
        maximizeBtn.setOnAction(e -> {
            if (stage.isMaximized()) {
                stage.setMaximized(false);
                maximizeBtn.setText("□");
            } else {
                stage.setMaximized(true);
                maximizeBtn.setText("❐");
            }
        });
        closeBtn.setOnAction(e -> stage.close());
        
        topBar.getChildren().addAll(titleLabel, searchField, userInfo, windowControls);
        setTop(topBar);
    }

    // 搜索事件处理方法
    private void setupSearchEvents(TextField searchTextField) {
        // 1. 回车键搜索事件
        searchTextField.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER) {
                String text = searchTextField.getText();
                if (text.trim().isEmpty()) {
                    return;
                }
                searchSingleMusic(text);
            }
        });

//        // 2. 实时搜索建议（防抖处理）
//        searchField.textProperty().addListener((observable, oldValue, newValue) -> {
//            if (searchTimer != null) {
//                searchTimer.cancel();
//            }
//
//            searchTimer = new Timer();
//            searchTimer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    Platform.runLater(() -> {
//                        if (!newValue.isEmpty() && newValue.length() >= 2) {
//                            showSearchSuggestions(newValue);
//                        } else {
//                            hideSearchSuggestions();
//                        }
//                    });
//                }
//            }, 300); // 300ms 防抖延迟
//        });

        // 3. 焦点事件
//        searchField.focusedProperty().addListener((observable, oldValue, newValue) -> {
//            if (newValue) {
//                // 获得焦点时显示搜索历史
//                showSearchHistory();
//                searchField.setStyle("-fx-background-radius: 20 20 0 0; -fx-border-radius: 20 20 0 0;");
//            } else {
//                // 失去焦点时隐藏建议框
//                hideSearchSuggestions();
//                searchField.setStyle("-fx-background-radius: 20; -fx-border-radius: 20;");
//            }
//        });
    }

    public void searchSingleMusic(String text) {
        ObservableList<SoundBO> list = playlistTableView.getItems();
        list.clear();
        new Thread(() -> {
            cloudMusicSpider.getPlayList(playListBOList);
            Platform.runLater(() -> {
                // tagsLabel.setText("标签：音乐");
                String trim = text.trim();
                // descLabel.setText("介绍：" + trim);
                // searchTiplabel.setText("");
                // labGroupName.setText(trim);
                /*Windows任务栏图标闪烁效果}*/
//                if (!mainStage.isFocused()) {
//                    mainStage.requestFocus();
//                }
//                tabPane.getSelectionModel().select(1);
//                leftListView.getSelectionModel().clearAndSelect(1);
                if (!list.isEmpty()) {
//                    songListCoverImageView.setImage(panDefaultImage);
//                    //songListCoverImageView.setImage(new Image(list.get(0).getImageUrl(), SONGLISTCOVERIMAGEVIEWSIZE, SONGLISTCOVERIMAGEVIEWSIZE, false, false));
//                    currentIndex = 0;
                }
            });
        }).start();
    }
    
    private void createLeftNav() {
        VBox leftNav = new VBox();
        leftNav.setPrefWidth(200);
        leftNav.setStyle("-fx-background-color: #fafafa; -fx-border-color: #e0e0e0; -fx-border-width: 0 1 0 0;");
        leftNav.setSpacing(0);
        
        // 导航项
        String[] navItems = {"推荐", "歌单", "本地音乐", "下载音乐", "本地音乐文件夹"};
        
        for (String item : navItems) {
            Label navItem = new Label(item);
            navItem.setPrefHeight(50);
            navItem.setStyle("-fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");
            navItem.setOnMouseEntered(e -> navItem.setStyle("-fx-background-color: #f0f0f0; -fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;"));
            navItem.setOnMouseExited(e -> navItem.setStyle("-fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;"));
            leftNav.getChildren().add(navItem);
        }

        // 遍历 leftNav 中的所有子节点并添加点击事件
        for (javafx.scene.Node node : leftNav.getChildren()) {
            if (node instanceof Label menuItem) {
                // 添加点击事件
                menuItem.setOnMouseClicked(event -> {
                    // 首先清除所有菜单项的高亮
                    for (javafx.scene.Node child : leftNav.getChildren()) {
                        if (child instanceof Label item) {
                            item.setStyle("-fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");
                        }
                    }

                    // 高亮当前选中的菜单项
                    menuItem.setStyle("-fx-background-color: #ec4141; -fx-text-fill: white; -fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");

                    // 根据菜单项文本执行不同的操作
                    String menuText = menuItem.getText();
                    handleMenuClick(menuText);
                });

                // 更新悬停效果，避免覆盖选中状态
                menuItem.setOnMouseEntered(e -> {
                    if (!menuItem.getStyle().contains("#ec4141")) {
                        menuItem.setStyle("-fx-background-color: #f0f0f0; -fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");
                    }
                });

                menuItem.setOnMouseExited(e -> {
                    if (!menuItem.getStyle().contains("#ec4141")) {
                        menuItem.setStyle("-fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");
                    }
                });
            }
        }

        // 默认选中第一个菜单项
        if (!leftNav.getChildren().isEmpty()) {
            Label firstItem = (Label) leftNav.getChildren().get(0);
            firstItem.setStyle("-fx-background-color: #ec4141; -fx-text-fill: white; -fx-font-size: 14px; -fx-padding: 0 20px; -fx-alignment: center-left;");
        }
        
        // 分隔线
        Separator separator = new Separator();
        leftNav.getChildren().add(separator);
        
        // 我的音乐部分
        Label myMusicTitle = new Label("我的音乐");
        myMusicTitle.setStyle("-fx-font-size: 12px; -fx-text-fill: #999; -fx-padding: 20 20 10 20;");
        
        String[] myMusicItems = {"我喜欢的音乐", "最近播放", "我的播客", "更多"};
        
        for (String item : myMusicItems) {
            Label musicItem = new Label(item);
            musicItem.setPrefHeight(40);
            musicItem.setStyle("-fx-font-size: 13px; -fx-padding: 0 20px; -fx-alignment: center-left;");
            musicItem.setOnMouseEntered(e -> musicItem.setStyle("-fx-background-color: #f0f0f0; -fx-font-size: 13px; -fx-padding: 0 20px; -fx-alignment: center-left;"));
            musicItem.setOnMouseExited(e -> musicItem.setStyle("-fx-font-size: 13px; -fx-padding: 0 20px; -fx-alignment: center-left;"));
            
            leftNav.getChildren().add(musicItem);
        }
        
        // 创建的歌单
        Label createdPlaylist = new Label("创建的歌单3");
        createdPlaylist.setPrefHeight(40);
        createdPlaylist.setStyle("-fx-font-size: 13px; -fx-padding: 0 20px; -fx-alignment: center-left;");
        
        leftNav.getChildren().addAll(myMusicTitle, createdPlaylist);
        
        setLeft(leftNav);
    }

    private void handleMenuClick(String menuText) {
        switch (menuText) {
            case "推荐":
                showRecommendationPage();
                break;
            case "精选":
                showFeaturedPage();
                break;
            case "播客":
                showPodcastPage();
                break;
            case "漫游":
                showExplorePage();
                break;
            case "关注":
                showFollowingPage();
                break;
            case "我的":
                showProfilePage();
                break;
            default:
                System.out.println("未知菜单: " + menuText);
        }
    }

    // 各个页面的具体实现方法
    private void showRecommendationPage() {
        System.out.println("切换到推荐页面");
        // 更新中心内容区域显示推荐内容
        updateContentArea("推荐内容区域");
    }

    private void showFeaturedPage() {
        System.out.println("切换到精选页面");
        updateContentArea("精选内容区域");
    }

    private void showPodcastPage() {
        System.out.println("切换到播客页面");
        updateContentArea("播客内容区域");
    }

    private void showExplorePage() {
        System.out.println("切换到漫游页面");
        updateContentArea("漫游内容区域");
    }

    private void showFollowingPage() {
        System.out.println("切换到关注页面");
        updateContentArea("关注内容区域");
    }

    private void showProfilePage() {
        System.out.println("切换到我的页面");
        updateContentArea("个人资料区域");
    }

    private void updateContentArea(String content) {
        // 实际应用中，这里应该更新主内容区域
//        Label contentLabel = new Label(content);
//        contentLabel.setStyle("-fx-font-size: 18px; -fx-padding: 20px;");

        // 假设有一个 contentPane 来显示主要内容
//        if (getCenter() instanceof ScrollPane scrollPane) {
//            scrollPane.setContent(contentLabel);
//        }

        createRecommendationContentPage();
    }
    
    private void createRecommendationContentPage() {
        ScrollPane contentPane = new ScrollPane();
        contentPane.setStyle("-fx-background: white; -fx-border-color: transparent;");
        
        VBox content = new VBox();
        content.setSpacing(20);
        content.setPadding(new Insets(20));
        
        // 推荐歌单标题
        Label recommendedTitle = new Label("推荐歌单");
        recommendedTitle.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
        
        // 歌单网格
        GridPane playlistGrid = new GridPane();
        playlistGrid.setHgap(15);
        playlistGrid.setVgap(15);
        playlistGrid.setPadding(new Insets(10, 0, 10, 0));
        
        // 添加歌单项
        String[][] playlists = {
            {"热歌榜", "145.7万"},
            {"民谣", "26.3万"},
            {"流行", "15.1万"},
            {"摇滚", "89.2万"},
            {"电子", "32.6万"},
            {"轻音乐", "47.8万"}
        };
        
        int col = 0;
        int row = 0;
        for (String[] playlist : playlists) {
            VBox playlistItem = createPlaylistItem(playlist[0], playlist[1]);
            playlistGrid.add(playlistItem, col, row);
            col++;
            if (col == 3) {
                col = 0;
                row++;
            }
        }

        VBox playingList = new VBox();
        playingList.setSpacing(10);
        playingList.setStyle("-fx-background-color: white; -fx-padding: 20; -fx-border-color: #e0e0e0; -fx-border-width: 1; -fx-border-radius: 5;");

        Label playingListTitle = new Label("正在播放");
        playingListTitle.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");

        if (!playList.isEmpty()) {
            ListView<SoundBO> listView = new ListView<>();
        }

        HBox soundFileArea = new HBox();
        soundFileArea.setSpacing(10);

        Button soundFileAddButton = new Button();
        soundFileAddButton.setText("添加音乐");
        soundFileAddButton.setStyle("-fx-background-color: #27ae60; -fx-text-fill: white; -fx-font-weight: bold;");
        soundFileAddButton.setOnAction(e -> handleAddMusic());

        Button soundFileRemoveButton = new Button();
        soundFileRemoveButton.setText("移除选中");
        soundFileRemoveButton.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white; -fx-font-weight: bold;");
        soundFileRemoveButton.setOnAction(e -> handleAddMusic());
        soundFileArea.getChildren().addAll(soundFileAddButton, soundFileRemoveButton);
        
        // 正在播放区域
        VBox nowPlaying = new VBox();
        nowPlaying.setSpacing(10);
        nowPlaying.setStyle("-fx-background-color: white; -fx-padding: 20; -fx-border-color: #e0e0e0; -fx-border-width: 1; -fx-border-radius: 5;");
        
        Label nowPlayingTitle = new Label("正在播放");
        nowPlayingTitle.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        HBox songInfo = new HBox();
        songInfo.setSpacing(15);
        songInfo.setAlignment(Pos.CENTER_LEFT);
        
        // 专辑封面
        albumArt = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/images/default-album.png"))));
        albumArt.setFitWidth(80);
        albumArt.setFitHeight(80);
        
        // 歌曲信息
        VBox songDetails = new VBox();
        songDetails.setSpacing(5);
        
        currentSongLabel = new Label(playList.get(currentSongIndex).getSoundName());
        currentSongLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        
        currentArtistLabel = new Label(playList.get(currentSongIndex).getArtistName());
        currentArtistLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
        
        songDetails.getChildren().addAll(currentSongLabel, currentArtistLabel);
        
        songInfo.getChildren().addAll(albumArt, songDetails);
        
        nowPlaying.getChildren().addAll(nowPlayingTitle, songInfo);
        
        content.getChildren().addAll(recommendedTitle, playlistGrid, soundFileArea, nowPlaying);
        contentPane.setContent(content);
        
        setCenter(contentPane);
    }

//    private void createContentArea() {
//        ScrollPane contentPane = new ScrollPane();
//        contentPane.setStyle("-fx-background: white; -fx-border-color: transparent;");
//
//        VBox content = new VBox();
//        content.setSpacing(20);
//        content.setPadding(new Insets(20));
//
//        // 推荐歌单标题
//        Label recommendedTitle = new Label("推荐歌单");
//        recommendedTitle.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
//
//        // 歌单网格
//        GridPane playlistGrid = new GridPane();
//        playlistGrid.setHgap(15);
//        playlistGrid.setVgap(15);
//        playlistGrid.setPadding(new Insets(10, 0, 10, 0));
//
//        // 添加歌单项
//        String[][] playlists = {
//                {"热歌榜", "145.7万"},
//                {"民谣", "26.3万"},
//                {"流行", "15.1万"},
//                {"摇滚", "89.2万"},
//                {"电子", "32.6万"},
//                {"轻音乐", "47.8万"}
//        };
//
//        int col = 0;
//        int row = 0;
//        for (String[] playlist : playlists) {
//            VBox playlistItem = createPlaylistItem(playlist[0], playlist[1]);
//            playlistGrid.add(playlistItem, col, row);
//            col++;
//            if (col == 3) {
//                col = 0;
//                row++;
//            }
//        }
//
//        VBox playingList = new VBox();
//        playingList.setSpacing(10);
//        playingList.setStyle("-fx-background-color: white; -fx-padding: 20; -fx-border-color: #e0e0e0; -fx-border-width: 1; -fx-border-radius: 5;");
//
//        Label playingListTitle = new Label("正在播放");
//        playingListTitle.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
//
//        if (!playList.isEmpty()) {
//            ListView<Song> listView = new ListView<>();
//        }
//
//        HBox soundFileArea = new HBox();
//        soundFileArea.setSpacing(10);
//
//        Button soundFileAddButton = new Button();
//        soundFileAddButton.setText("添加音乐");
//        soundFileAddButton.setStyle("-fx-background-color: #27ae60; -fx-text-fill: white; -fx-font-weight: bold;");
//        soundFileAddButton.setOnAction(e -> handleAddMusic());
//
//        Button soundFileRemoveButton = new Button();
//        soundFileRemoveButton.setText("移除选中");
//        soundFileRemoveButton.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white; -fx-font-weight: bold;");
//        soundFileRemoveButton.setOnAction(e -> handleAddMusic());
//        soundFileArea.getChildren().addAll(soundFileAddButton, soundFileRemoveButton);
//
//        // 正在播放区域
//        VBox nowPlaying = new VBox();
//        nowPlaying.setSpacing(10);
//        nowPlaying.setStyle("-fx-background-color: white; -fx-padding: 20; -fx-border-color: #e0e0e0; -fx-border-width: 1; -fx-border-radius: 5;");
//
//        Label nowPlayingTitle = new Label("正在播放");
//        nowPlayingTitle.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
//
//        HBox songInfo = new HBox();
//        songInfo.setSpacing(15);
//        songInfo.setAlignment(Pos.CENTER_LEFT);
//
//        // 专辑封面
//        albumArt = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/images/default-album.png"))));
//        albumArt.setFitWidth(80);
//        albumArt.setFitHeight(80);
//
//        // 歌曲信息
//        VBox songDetails = new VBox();
//        songDetails.setSpacing(5);
//
//        currentSongLabel = new Label(playList.get(currentSongIndex).getTitle());
//        currentSongLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
//
//        currentArtistLabel = new Label(playList.get(currentSongIndex).getArtist());
//        currentArtistLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
//
//        songDetails.getChildren().addAll(currentSongLabel, currentArtistLabel);
//
//        songInfo.getChildren().addAll(albumArt, songDetails);
//
//        nowPlaying.getChildren().addAll(nowPlayingTitle, songInfo);
//
//        content.getChildren().addAll(recommendedTitle, playlistGrid, soundFileArea, nowPlaying);
//        contentPane.setContent(content);
//
//        setCenter(contentPane);
//    }

    private void handleAddMusic() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择音乐文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("音频文件", "*.mp3", "*.wav", "*.m4a", "*.aac"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(null);
        if (selectedFiles != null) {
            for (File file : selectedFiles) {
                if (!musicFiles.contains(file)) {
                    musicFiles.add(file);

                    SoundBO song = new SoundBO();
                    song.setSoundName(file.getName());
                    playList.add(song);
                }
            }

            // 如果当前没有在播放，自动播放第一首
            if (mediaPlayer == null && !musicFiles.isEmpty()) {
                playSelectedSong(0);
            }
        }
    }

    private void handleRemoveMusic() {
//        int selectedIndex = playlistView.getSelectionModel().getSelectedIndex();
//        if (selectedIndex >= 0) {
//            // 如果正在播放被删除的歌曲，先停止
//            if (selectedIndex == currentSongIndex && mediaPlayer != null) {
//                mediaPlayer.stop();
//                mediaPlayer = null;
//            }
//
//            musicFiles.remove(selectedIndex);
//            playlist.remove(selectedIndex);
//
//            // 调整当前歌曲索引
//            if (currentSongIndex >= selectedIndex) {
//                currentSongIndex = Math.max(0, currentSongIndex - 1);
//            }
//
//            // 如果还有歌曲，播放当前索引的歌曲
//            if (!musicFiles.isEmpty()) {
//                playSelectedSong(currentSongIndex);
//            } else {
//                currentSongLabel.setText("没有歌曲在播放");
//                albumArtView.setImage(getDefaultAlbumArt());
//            }
//        }
    }

    private void playSelectedSong(int index) {
//        if (index < 0 || index >= musicFiles.size()) return;
//
//        // 停止当前播放
//        if (mediaPlayer != null) {
//            mediaPlayer.stop();
//            stopProgressTimer();
//        }
//
//        currentSongIndex = index;
//        File musicFile = musicFiles.get(index);
//
//        try {
//            Media media = new Media(musicFile.toURI().toString());
//            mediaPlayer = new MediaPlayer(media);
//
//            // 设置媒体播放器事件
//            mediaPlayer.setOnReady(() -> {
//                currentSongLabel.setText("正在播放: " + musicFile.getName());
//                updateButtonStates();
//                updateTimeLabels(Duration.ZERO, mediaPlayer.getTotalDuration());
//
//                // 自动播放
//                handlePlay();
//            });
//
//            // 自动播放下一首
//            mediaPlayer.setOnEndOfMedia(this::handleNext);
//
//            mediaPlayer.setOnError(() -> {
//                log.error("媒体播放错误: {} ", mediaPlayer.getError().getMessage());
//                showAlert("播放错误", "无法播放文件: " + musicFile.getName());
//            });
//
//            // 更新列表选择
//            playlistView.getSelectionModel().select(index);
//
//        } catch (Exception e) {
//            log.error("创建媒体播放器失败", e);
//            showAlert("错误", "无法加载文件: " + musicFile.getName());
//        }
    }

    private void stopProgressTimer() {
        if (progressTimeline != null) {
            progressTimeline.stop();
        }
    }

    private void startProgressTimer() {
        stopProgressTimer();

        progressTimeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            if (mediaPlayer != null) {
                Duration currentTime = mediaPlayer.getCurrentTime();
                Duration totalDuration = mediaPlayer.getTotalDuration();

                if (totalDuration.greaterThan(Duration.ZERO)) {
                    double progress = (currentTime.toMillis() / totalDuration.toMillis()) * 100.0;
                    progressSlider.setValue(progress);
                    updateTimeLabels(currentTime, totalDuration);
                }
            }
        }));
        progressTimeline.setCycleCount(Timeline.INDEFINITE);
        progressTimeline.play();
    }

    private void updateTimeLabels(Duration currentTime, Duration totalDuration) {
        currentTimeLabel.setText(formatDurationTime(currentTime));
        totalTimeLabel.setText(formatDurationTime(totalDuration));
    }
    
    private VBox createPlaylistItem(String title, String playCount) {
        VBox item = new VBox();
        item.setSpacing(5);
        item.setStyle("-fx-cursor: hand;");
        
        ImageView cover = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/images/default-album.png"))));
        cover.setFitWidth(150);
        cover.setFitHeight(150);
        cover.setStyle("-fx-border-radius: 5;");
        
        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-size: 14px;");
        
        Label countLabel = new Label(playCount);
        countLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #999;");
        
        item.getChildren().addAll(cover, titleLabel, countLabel);
        
        // 点击事件
        item.setOnMouseClicked(e -> {
            // 模拟播放点击的歌单
            System.out.println("播放歌单: " + title);
        });
        
        return item;
    }
    
    private void createPlayerControl() {
        if (playList.isEmpty()) {
            return;
        }

        HBox controlBar = new HBox();
        controlBar.setStyle("-fx-background-color: #2d2d2d; -fx-padding: 10;");
        controlBar.setAlignment(Pos.CENTER);
        controlBar.setSpacing(20);
        
        // 歌曲信息
        VBox songInfo = new VBox();
        songInfo.setAlignment(Pos.CENTER_LEFT);
        
        Label songTitle = new Label(playList.get(currentSongIndex).getSoundName());
        songTitle.setStyle("-fx-text-fill: white; -fx-font-size: 14px;");
        
        Label artist = new Label(playList.get(currentSongIndex).getArtistName());
        artist.setStyle("-fx-text-fill: #ccc; -fx-font-size: 12px;");
        
        songInfo.getChildren().addAll(songTitle, artist);
        
        // 播放控制按钮
        HBox controls = new HBox();
        controls.setAlignment(Pos.CENTER);
        controls.setSpacing(15);
        
        prevButton = createControlButton("⏮", "#fff");
        playButton = createControlButton("⏯", "#fff");
        nextButton = createControlButton("⏭", "#fff");
        
        // 喜欢按钮
        likeButton = createControlButton("♥", "#ccc");
        
        controls.getChildren().addAll(prevButton, playButton, nextButton, likeButton);
        
        // 进度条区域
        VBox progressArea = new VBox();
        progressArea.setAlignment(Pos.CENTER);
        progressArea.setSpacing(5);
        
        HBox timeLabels = new HBox();
        timeLabels.setAlignment(Pos.CENTER);
        
        currentTimeLabel = new Label("00:00");
        currentTimeLabel.setStyle("-fx-text-fill: white; -fx-font-size: 12px;");
        
        progressSlider = new Slider();
        progressSlider.setPrefWidth(400);
        
        totalTimeLabel = new Label(formatTime(playList.get(currentSongIndex).getDuration()));
        totalTimeLabel.setStyle("-fx-text-fill: white; -fx-font-size: 12px;");
        
        timeLabels.getChildren().addAll(currentTimeLabel, progressSlider, totalTimeLabel);
        HBox.setHgrow(progressSlider, Priority.ALWAYS);
        
        progressArea.getChildren().add(timeLabels);
        
        // 音量控制
        HBox volumeControl = new HBox();
        volumeControl.setAlignment(Pos.CENTER_RIGHT);
        volumeControl.setSpacing(10);
        
        Label volumeIcon = new Label("🔊");
        volumeIcon.setStyle("-fx-text-fill: white;");
        
        Slider volumeSlider = new Slider();
        volumeSlider.setPrefWidth(100);
        volumeSlider.setValue(50);
        
        volumeControl.getChildren().addAll(volumeIcon, volumeSlider);
        
        // 布局控制
        HBox.setHgrow(songInfo, Priority.NEVER);
        HBox.setHgrow(progressArea, Priority.ALWAYS);
        HBox.setHgrow(volumeControl, Priority.NEVER);
        
        controlBar.getChildren().addAll(songInfo, controls, progressArea, volumeControl);
        setBottom(controlBar);
    }
    
    private Button createControlButton(String text, String color) {
        Button button = new Button(text);
        button.setStyle(String.format(
            "-fx-background-color: transparent; -fx-text-fill: %s; -fx-font-size: 16px; -fx-border-color: transparent;",
            color
        ));
        
        button.setOnMouseEntered(e -> button.setStyle(
            String.format("-fx-background-color: #444; -fx-text-fill: %s; -fx-font-size: 16px; -fx-border-color: transparent;", color)
        ));
        button.setOnMouseExited(e -> button.setStyle(
            String.format("-fx-background-color: transparent; -fx-text-fill: %s; -fx-font-size: 16px; -fx-border-color: transparent;", color)
        ));
        
        return button;
    }
    
    private void setupEventHandlers() {
        // 播放/暂停按钮
        if (Objects.nonNull(playButton)) {
            playButton.setOnAction(e -> togglePlayback());
        }

        
        // 上一首/下一首
        if (Objects.nonNull(prevButton)) {
            prevButton.setOnAction(e -> playPrevious());
        }
        if (Objects.nonNull(nextButton)) {
            nextButton.setOnAction(e -> playNext());
        }
        
        // 喜欢按钮
        if (Objects.nonNull(likeButton)) {
            likeButton.setOnAction(e -> toggleLike());
        }

        // 进度条事件
        if (Objects.nonNull(progressSlider)) {
            progressSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
                if (progressSlider.isValueChanging() && mediaPlayer != null) {
                    mediaPlayer.seek(Duration.seconds(newVal.doubleValue()));
                }
            });
        }
    }
    
    private void togglePlayback() {
        if (mediaPlayer == null) return;
        
        if (isPlaying) {
            mediaPlayer.pause();
            playButton.setText("⏯");
        } else {
            mediaPlayer.play();
            playButton.setText("⏸");
        }
        isPlaying = !isPlaying;
    }
    
    private void playPrevious() {
        currentSongIndex = (currentSongIndex - 1 + playList.size()) % playList.size();
        loadSong(currentSongIndex);
        updateUI();
    }
    
    private void playNext() {
        currentSongIndex = (currentSongIndex + 1) % playList.size();
        loadSong(currentSongIndex);
        updateUI();
    }
    
    private void toggleLike() {
        likeButton.setStyle(likeButton.getStyle().contains("#ec4141") ? 
            "-fx-text-fill: #ccc;" : "-fx-text-fill: #ec4141;");
    }
    
    private void loadSong(int index) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
        
        SoundBO sound = playList.get(index);
        // 这里应该是实际音频文件的路径
        String musicFile = "path/to/your/music/file.mp3"; // 替换为实际文件路径
        
        try {
            Media media = new Media(new File(musicFile).toURI().toString());
            mediaPlayer = new MediaPlayer(media);
            
            // 设置播放完成事件
            mediaPlayer.setOnEndOfMedia(this::playNext);
            
            // 更新进度条
            mediaPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
                double current = newTime.toSeconds();
                double total = mediaPlayer.getTotalDuration().toSeconds();
                progressSlider.setValue(current);
                currentTimeLabel.setText(formatTime((int) current));
                
                if (!progressSlider.isValueChanging()) {
                    progressSlider.setMax(total);
                }
            });
            
            if (isPlaying) {
                mediaPlayer.play();
            }
            
        } catch (Exception e) {
            System.out.println("无法加载音频文件: " + e.getMessage());
        }
    }
    
    private void updateUI() {
        SoundBO currentSong = playList.get(currentSongIndex);
        currentSongLabel.setText(currentSong.getSoundName());
        currentArtistLabel.setText(currentSong.getArtistName());
        totalTimeLabel.setText(formatTime(currentSong.getDuration()));
    }

    private String formatDurationTime(Duration duration) {
        int minutes = (int) duration.toMinutes();
        int seconds = (int) duration.toSeconds() % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
    
    private String formatTime(int seconds) {
        int minutes = seconds / 60;
        int secs = seconds % 60;
        return String.format("%02d:%02d", minutes, secs);
    }
//
//    // 内部歌曲类
//    private static class Song {
//        private final String title;
//        private final String artist;
//        private final int duration; // 秒
//        private final String coverArt;
//
//        public Song(String title, String artist, int duration, String coverArt) {
//            this.title = title;
//            this.artist = artist;
//            this.duration = duration;
//            this.coverArt = coverArt;
//        }
//
//        public String getTitle() { return title; }
//        public String getArtist() { return artist; }
//        public int getDuration() { return duration; }
//        public String getCoverArt() { return coverArt; }
//    }
}